import { t } from 'i18next'
import create from 'zustand'
import createVanilla from 'zustand/vanilla'
import { subscribeWithSelector } from 'zustand/middleware'
import { store as tableDcsStore } from '@/pages/manager/blocks/main/table/dcs/store'
import {
	fetchSetMeetingInfo,
	fetchCheckMeetingName,
	fetchCalcMinute,
	fetchDelayCheck,
	fetchNoDelayMeeting,
	fetchDelayMeeting,
} from '@/api/manager/meetingInfoSet/index'
import { useMccStore } from '../../store'
import Alert, { Confirm } from '@/components/Alert'
import { useGlobalStore } from '@/store/global'
import { fetchGetPlatformServiceUrl } from '@/api/global'
import { useMonitorStore } from '../monitor/store'

const initialState = {
	showDelayMeeting: false,
	showMeetingInfo: false,
	password: '',
	name: '',
	meetingClosed: false,
	meetingSafe: false,
	watermark: false,
	enableRtc: false,
	loginFree: { checked: false, value: 1 },
	doubleFlowLimit: 0,
	showDCSChoosen: false,
	dcsMode: 2,
	meetingMoid: '',
	e164: '',
	customMinuter: 30,
	inputMinuter: '',
	showInputMinter: false,
	remainTime: t('正在获取'),
	fromComet: false,
	remainTimeColor: '',
	delayMeetingLock: false,
	hasEndMeetingDialog: false,
}
type MeetingInfoState = meetingInfoState & {
	update: (d: Partial<meetingInfoState>) => void
	fetchInit: () => void // 初始化会议信息设置
	initDelayMeeting: (d: form) => void //初始化延迟会议弹窗 0  点击  1 comted
	updateMeetingInfo: () => void /**修改会议参数 */
	checkMeetingName: () => Promise<boolean> //会议名称是否可用
	delayMeeting: () => void //延长会议
	noDelayMeeting: () => void //不延迟会议
	showTime: (d: string) => void
	endMeeting: (d: { reason: string }) => void
}
interface form {
	from: 0 | 1
	time?: number
}
interface meetingInfoState {
	e164: string // 会议e164
	showMeetingInfo: boolean // 是否显示会议信息设置
	password: string // 会议密码
	name: string // 会议名称
	meetingClosed: boolean // 会议免打扰
	meetingSafe: boolean // 会议可见
	watermark: boolean // 会议水印
	enableRtc: boolean // rtc会议
	loginFree: { checked: boolean; value: number } // 免登陆
	doubleFlowLimit: number // 会议双流权限
	showDCSChoosen: boolean // 协作权限控制
	dcsMode: number // dcs模式
	meetingMoid: string //会议moid
	showDelayMeeting: boolean // 是否显示延迟会议
	customMinuter: number // 会议延迟时间  0 30 60 90
	inputMinuter: string // 输入的会议时间
	showInputMinter: boolean //是否显示自定义输入框
	remainTime: string // 会议结束提示时间
	remainTimeColor: string // 会议结束提示时间颜色
	fromComet: boolean // 延迟会议展示是否来自comted
	delayMeetingLock: boolean //延迟会议接口锁  防止调用接口时 来comted推送
	hasEndMeetingDialog: boolean //结束会议弹窗是否存在
}
export const store = createVanilla<MeetingInfoState>()(
	subscribeWithSelector((set, get) => ({
		...initialState,
		update: (d) => {
			set({ ...d })
		},
		reset: () => set(initialState),
		fetchInit: async () => {
			const meetingInfo = useMccStore.getState().mccInfo
			const enableDcs = !!useGlobalStore.getState().user?.enable_dcs
			const dcsMode = tableDcsStore.getState().dcsMode
			set({
				password: meetingInfo.password ? '******' : '',
				name: meetingInfo.subject,
				meetingClosed: meetingInfo.meetingClosed === 1 ? true : false,
				meetingSafe: meetingInfo.meetingSafe === 0 ? true : false,
				watermark: meetingInfo.watermark === 1 ? true : false,
				enableRtc: meetingInfo.enableRtc ? true : false,
				loginFree: { checked: meetingInfo.allowAnonymousMt ? true : false, value: 1 },
				doubleFlowLimit: meetingInfo.doubleFlowLimit,
				showDCSChoosen: enableDcs && dcsMode !== 0,
				dcsMode: dcsMode === 1 ? 1 : 2,
				meetingMoid: meetingInfo.meetingMoid,
				e164: meetingInfo.e164,
				showMeetingInfo: true,
			})
		},
		updateMeetingInfo: async () => {
			const {
				name,
				password,
				meetingSafe,
				meetingClosed,
				doubleFlowLimit,
				loginFree,
				watermark,
				dcsMode,
				meetingMoid,
				e164,
			} = get()
			const meetingInfo = useMccStore.getState().mccInfo
			const param = {
				name: name,
				password: password === '******' ? meetingInfo.password ?? '' : password,
				meeting_safe: meetingSafe ? 0 : 1,
				meeting_closed: meetingClosed ? 1 : 0,
				dual_mode: doubleFlowLimit,
				allow_anonymous_mt: loginFree.checked ? 1 : 0,
				watermark: watermark ? 1 : 0,
				dcs_mode: dcsMode,
			}
			let r = await fetchSetMeetingInfo(meetingMoid, e164, param)
			if (r) {
				useMonitorStore.getState().webToNativeEntry('UpdateMeetingName', {
					event: 'KCMP_UPDATE_CONF_NAME_NTF',
					conf_id: e164, //即会议E164
					conf_name: name, //新的会议名称
				})
			}
			set({ showMeetingInfo: false })
		},
		checkMeetingName: async () => {
			const { name } = get()
			const subject = useMccStore.getState().mccInfo.subject.trim()
			if (name.trim() === subject) {
				return true
			}
			const res = await fetchCheckMeetingName({ conf_name: name })
			return res
		},
		delayMeeting: async () => {
			const { remainTime, customMinuter, inputMinuter, meetingMoid } = get()
			let reg = /^([1-9]\d{0,3})$/
			if (remainTime === t('手动结束')) {
				set({ showDelayMeeting: false })
				Alert(t('您已开启永久会议，无需延长会议操作'))
				return false
			}
			let delay = 0
			if (customMinuter === 0) {
				//自定义时间
				delay = Number(inputMinuter)
				if (delay === 0) {
					Alert(t('请确定会议延长时间'))
					return false
				} else if (!reg.test(inputMinuter) || delay > 4320 || delay < 1) {
					Alert(t('会议延长范围为1~4320分钟'))
					return false
				}
			} else {
				delay = customMinuter
			}
			set({ showDelayMeeting: false, delayMeetingLock: true })
			const checkResult = await fetchDelayCheck(meetingMoid, delay)
			if (checkResult.success) {
				if (checkResult.data && checkResult.data.delay_meeting) {
					const res = await fetchDelayMeeting(meetingMoid, delay)
					res.success ? Alert(t('延长会议时间成功！')) : Alert(t('当前会议资源紧张，暂时无法延长会议'))
				} else {
					Confirm(t('延长会议会导致后续其他预约的会议无法正常召开，确定延长？'), async () => {
						const res = await fetchDelayMeeting(meetingMoid, delay)
						res.success ? Alert(t('延长会议时间成功！')) : Alert(t('当前会议资源紧张，暂时无法延长会议'))
					})
				}
			} else {
				Alert(t('当前会议资源紧张，暂时无法延长会议'))
			}
			set({ delayMeetingLock: false })
		},
		noDelayMeeting: async () => {
			const { meetingMoid } = get()
			const result = await fetchNoDelayMeeting(meetingMoid)
			if (result.success) {
				set({ showDelayMeeting: false })
			} else {
				Alert(t('操作失败'))
			}
		},
		initDelayMeeting: async (data) => {
			const meetingMoid = useMccStore.getState().mccInfo.meetingMoid
			const { delayMeetingLock } = get()
			const { showTime } = get()
			if (data.from === 0) {
				const result = await fetchCalcMinute(meetingMoid)
				if (result.success) {
					if (result.data) {
						showTime(result.data.time)
					} else {
						showTime(t('获取失败'))
					}
				} else {
					showTime(t('获取失败'))
				}
				set({
					showDelayMeeting: true,
					fromComet: false,
					meetingMoid: meetingMoid,
					customMinuter: 30,
					inputMinuter: '',
					showInputMinter: false,
				})
			} else {
				if (delayMeetingLock) {
					return false
				}
				if (data.time) {
					showTime(data.time + '')
				}
				set({
					showDelayMeeting: true,
					fromComet: true,
					meetingMoid: meetingMoid,
					showInputMinter: false,
					customMinuter: 30,
					inputMinuter: '',
				})
			}
		},
		showTime: (remainTime: string) => {
			if (remainTime === t('手动结束') || remainTime === t('正在获取') || remainTime === t('获取失败')) {
				set({ remainTime: remainTime })
			} else {
				if (Number(remainTime) <= 15) {
					set({ remainTime: t('{{minute}}分钟', { minute: remainTime }), remainTimeColor: '#d21e1e' })
				} else {
					set({ remainTime: t('{{minute}}分钟', { minute: remainTime }), remainTimeColor: '#777' })
				}
			}
		},
		endMeeting: ({ reason }) => {
			const { hasEndMeetingDialog } = get()
			if (!hasEndMeetingDialog) {
				set({ hasEndMeetingDialog: true })
				let msg = reason === '8' ? t('因发生故障，会议已备份召开') : t('会议已结束')
				Alert(msg, () => {
					set({ hasEndMeetingDialog: false })
					fetchGetPlatformServiceUrl()
						.then((data) => {
							window.location.href = data + '/index.html'
						})
						.catch((err) => {
							window.location.href = '/meeting/index.html'
						})
				})
			}
		},
	}))
)
export const useSettingMeetingStore = create(store)
